package storage.indexing.bTree;

import java.util.ArrayList;

import represent.type.*;
import utils.Lib;

public class BTreeLeafNode<T extends Type> extends BTreeNode<T> {

	private ArrayList<Integer>[] tuples = (ArrayList<Integer>[]) new ArrayList[POINTER_COUNT - 1];
	private BTreeLeafNode<T> nextLeaf;
	
	public BTreeLeafNode(BTree<T> tree) {
		super(tree);
	}
	
	public BTreeLeafNode(BTreeInternalNode<T> father) {
		super(father);
	}
	
	@Override
	protected BTreeNode<T> createNode() {
		return new BTreeLeafNode<T>(father);
	}
	
	@Override
	protected void update(BTreeNode<T> next, int pos) {
		Lib.assertTrue(next instanceof BTreeLeafNode<?>);
		BTreeLeafNode<T> lNext = (BTreeLeafNode<T>) next;
		
		// update keys and tuples for leaf node
		for (int i = pos + 1; i < POINTER_COUNT; ++i) {
			lNext.keys[i - pos - 1] = keys[i];
			keys[i] = null;
			lNext.tuples[i - pos] = tuples[i];
			tuples[i] = null;
			--size;
			++next.size;
		}
		
		this.nextLeaf = lNext;
	}
	
	protected void insert(T key, int rid, BTreeNode<T> pointer) {
		for (int i = 0; i < size; ++i)
			if (keys[i].compareTo(key) == 0) {
				tuples[i].add(rid);
				return;
			}
		super.insert(key, rid, pointer);
	}

	protected void insertKey(T key, int pos, int rid, BTreeNode<T> pointer) {
		// insert key and rid only
		++size;
		for (int i = size; i > pos; --i) {
			keys[i] = keys[i - 1];
			tuples[i] = tuples[i - 1];
		}
		keys[pos] = key;
		tuples[pos] = new ArrayList<Integer>();
		tuples[pos].add(rid);
	}
	
	protected void deleteKey(T key, int pos, int rid) {
		--size;
		for (int i = pos; i < size; ++i) {
			keys[i] = keys[i + 1];
			tuples[i] = tuples[i + 1];
		}
	}

}
